package com.cfweb.util;

import java.io.File;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.james.mime4j.util.CharsetUtil;

public class HttpClientUtil {
	private static int TIMEOUT=12000000;
	/**
	 * 
	 * @param url
	 * @param params
	 * @param headers
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResponse doGet(String url,
			Map<String, String> params, Map<String, String> headers,boolean trustSelfSignedCerts)
			throws Exception {
		HttpClient httpClient = new DefaultHttpClient();
		if(trustSelfSignedCerts){
			httpClient.getConnectionManager().getSchemeRegistry().register(getHttpsScheme());  
		} 
		HttpParams TimeParams=httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(TimeParams,TIMEOUT); 
		HttpGet httpGet = null;
		try {
			httpGet = new HttpGet(url);
			setHeaders(httpGet, headers);
			HttpResponse response = httpClient.execute(httpGet);
			System.out.println(response.toString());
			System.out.println(response);
			HttpEntity resentity = response.getEntity();
			String content = null;
			if (resentity != null) {
				content = EntityUtils.toString(resentity, "UTF-8");
			}
			return new HttpClientResponse(response.getStatusLine()
					.getStatusCode(), content);
		} catch (Exception e) {
			throw e;
		} finally {
			if (httpGet != null) {
				httpGet.abort();
			}
			httpClient.getConnectionManager().shutdown();
		}

	}

	/**
	 * contentType:application/x-www-form-urlencoded
	 * 
	 * @param url
	 * @param params
	 * @param headers
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResponse doPost(String url,
			Map<String, String> params, Map<String, String> headers,boolean trustSelfSignedCerts)
			throws Exception {
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		try {
			httpClient = new DefaultHttpClient();
			if(trustSelfSignedCerts){
				httpClient.getConnectionManager().getSchemeRegistry().register(getHttpsScheme());  
			}
			HttpParams TimeParams=httpClient.getParams();
			HttpConnectionParams.setConnectionTimeout(TimeParams,TIMEOUT);
			httpPost = new HttpPost(url);
			setHeaders(httpPost, headers);
			List<NameValuePair> requestParams = new ArrayList<NameValuePair>();
			// 设置Http Post数据
			if (params != null) {
				for (Map.Entry<String, String> entry : params.entrySet()) {
					requestParams.add(new BasicNameValuePair(entry.getKey(),
							entry.getValue()));
				}
			}
			HttpEntity entity = new UrlEncodedFormEntity(requestParams, "utf-8");
			httpPost.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity resentity = response.getEntity();
			String content = null;
			if (resentity != null) {
				content = EntityUtils.toString(resentity, "UTF-8");
			}
			return new HttpClientResponse(response.getStatusLine()
					.getStatusCode(), content);
		} catch (Exception e) {
			throw e;
		} finally {
			httpPost.abort();
			httpClient.getConnectionManager().shutdown();
		}
	}

	private static Scheme getHttpsScheme() throws NoSuchAlgorithmException, KeyManagementException {
		SSLContext sslcontext = SSLContext.getInstance("TLS"); 
        sslcontext.init(null, null, null);
        SSLSocketFactory sf = new SSLSocketFactory(  
        	    sslcontext,  
        	    SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
      return new Scheme("https", 443, sf);
	}

	public static HttpClientResponse doPut(String url,
			Map<String, Object> params, Map<String, String> headers,boolean trustSelfSignedCerts)
			throws Exception {
		HttpClient httpClient = null;
		HttpPut httpPut = null;
		try {
			httpClient = new DefaultHttpClient();
			if(trustSelfSignedCerts){
				httpClient.getConnectionManager().getSchemeRegistry().register(getHttpsScheme());  
			}
			HttpParams TimeParams=httpClient.getParams();
			HttpConnectionParams.setConnectionTimeout(TimeParams,TIMEOUT);
			httpPut = new HttpPut(url);
			setHeaders(httpPut, headers);
			if(params!=null){
				HttpEntity entity = new StringEntity(
						JsonUtil.convertToJson(params), "utf-8");
				httpPut.setEntity(entity);
			}
			HttpResponse response = httpClient.execute(httpPut);
			HttpEntity resentity = response.getEntity();
			String content = null;
			if (resentity != null) {
				content = EntityUtils.toString(resentity, "UTF-8");
			}
			System.out.println(content);
			return new HttpClientResponse(response.getStatusLine()
					.getStatusCode(), content);
			// String content = EntityUtils.toString(returnEntity, "UTF-8");
		} catch (Exception e) {
			throw e;
		} finally {
			httpPut.abort();
			httpClient.getConnectionManager().shutdown();
		}
	}
	
	public static HttpClientResponse doResouceMatchPut(String url,Map<String,Object> params,Map<String,String> headers,boolean trustSelfSignedCerts) throws Exception{
		HttpClient httpClient = null;
		HttpPut httpPut = null;
		try {
			httpClient =  new DefaultHttpClient();
			if(trustSelfSignedCerts){
				httpClient.getConnectionManager().getSchemeRegistry().register(getHttpsScheme());  
			}
			HttpParams TimeParams=httpClient.getParams();
			HttpConnectionParams.setConnectionTimeout(TimeParams,TIMEOUT);
			httpPut = new HttpPut(url);
			setHeaders(httpPut,headers);
			HttpEntity entity = new StringEntity((String) params.get("resources"), "utf-8");
			httpPut.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPut);
			HttpEntity resentity = response.getEntity(); 
			String content=null;
			if(resentity!=null){
				content=EntityUtils.toString(resentity, "UTF-8");
			}
			return new HttpClientResponse(response.getStatusLine().getStatusCode(), content);
			//String content = EntityUtils.toString(returnEntity, "UTF-8"); 
		} catch (Exception e) {
			throw e;
		} finally {
			httpPut.abort(); 
	        httpClient.getConnectionManager().shutdown();
		}
	}

	/**
	 * 
	 * @param url
	 * @param params
	 * @param headers
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResponse doDelete(String url,
			Map<String, Object> params, Map<String, String> headers,boolean trustSelfSignedCerts)
			throws Exception {
		HttpClient httpClient = null;
		HttpDelete httpDelete = null;
		try {
			httpClient = new DefaultHttpClient();
			if(trustSelfSignedCerts){
				httpClient.getConnectionManager().getSchemeRegistry().register(getHttpsScheme());  
			}
			HttpParams TimeParams=httpClient.getParams();
			HttpConnectionParams.setConnectionTimeout(TimeParams,TIMEOUT);
			httpDelete = new HttpDelete(url);
			setHeaders(httpDelete, headers);
			HttpResponse response = httpClient.execute(httpDelete);
			HttpEntity resentity = response.getEntity();
			String content = null;
			if (resentity != null) {
				content = EntityUtils.toString(resentity, "UTF-8");
			}
			return new HttpClientResponse(response.getStatusLine()
					.getStatusCode(), content);
			// String content = EntityUtils.toString(returnEntity, "UTF-8");
		} catch (Exception e) {
			throw e;
		} finally {
			httpDelete.abort();
			httpClient.getConnectionManager().shutdown();
		}
	}

	/**
	 * content-type:application/josn
	 * 
	 * @param url
	 * @param params
	 * @param headers
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResponse doPostWithJsonType(String url,
			Map<String, Object> params, Map<String, String> headers,boolean trustSelfSignedCerts)
			throws Exception {
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		try {
			httpClient = new DefaultHttpClient();
			if(trustSelfSignedCerts){
				httpClient.getConnectionManager().getSchemeRegistry().register(getHttpsScheme());  
			}
			httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT);
			httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT);
//			HttpParams TimeParams=httpClient.getParams();
//			HttpConnectionParams.setConnectionTimeout(TimeParams,TIMEOUT);
//			HttpConnectionParams.setSoTimeout(TimeParams, TIMEOUT);
			httpPost = new HttpPost(url);
			setHeaders(httpPost, headers);
			if(params!=null){
				HttpEntity entity = new StringEntity(
						JsonUtil.convertToJson(params), "utf-8");
				httpPost.setEntity(entity);
			}
			long startTime=System.currentTimeMillis();
			HttpResponse response = httpClient.execute(httpPost);
			long endTime=System.currentTimeMillis();
			HttpEntity resentity = response.getEntity();
			System.out.println("---------");
			System.out.println(response.toString());
			System.out.println("程序运行时间： "+(startTime-endTime)+"ms");
			String content = null;
			if (resentity != null) {
				content = EntityUtils.toString(resentity, "UTF-8");
			}
			System.out.println(content);
			return new HttpClientResponse(response.getStatusLine()
					.getStatusCode(), content);
			// String content = EntityUtils.toString(returnEntity, "UTF-8");
		} catch (Exception e) {
			throw e;
		} finally {
			httpPost.abort();
			httpClient.getConnectionManager().shutdown();
		}
	}
	

	public static HttpClientResponse doPutWithFile(String url,
			Map<String, Object> params, Map<String, String> headers,boolean trustSelfSignedCerts)
			throws Exception {
		HttpClient httpClient = null;
		HttpPut httpPut = null;
		try {
			httpClient = new DefaultHttpClient();
			if(trustSelfSignedCerts){
				httpClient.getConnectionManager().getSchemeRegistry().register(getHttpsScheme());  
			}
			HttpParams TimeParams=httpClient.getParams();
			HttpConnectionParams.setConnectionTimeout(TimeParams,TIMEOUT);
			httpPut = new HttpPut(url);
			setHeaders(httpPut, headers);
			FileBody bin = new FileBody((File) params.get("file"));
			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE, null,
					CharsetUtil.UTF_8);
			entity.addPart("application", bin);
			entity.addPart("resources",
					new StringBody((String) params.get("resources")));
			httpPut.addHeader(entity.getContentType());
			httpPut.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPut);
			HttpEntity resentity = response.getEntity();
			String content = null;
			if (resentity != null) {
				content = EntityUtils.toString(resentity, "UTF-8");
			}
			System.out.println("-------");
			System.out.println(content);
			return new HttpClientResponse(response.getStatusLine()
					.getStatusCode(), content);
			// String content = EntityUtils.toString(returnEntity, "UTF-8");
		} catch (Exception e) {
			throw e;
		} finally {
			httpPut.abort();
			httpClient.getConnectionManager().shutdown();
		}
	}

	private static void setHeaders(HttpRequestBase method,
			Map<String, String> headers) {
		if (headers == null) {
			return;
		}
		for (Map.Entry<String, String> entry : headers.entrySet()) {
			method.addHeader(entry.getKey(), entry.getValue());
		}
	}

}
